package com.jzg.jcptadmin.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.adpter.TaskViewStadusAdapter;
import com.jzg.jcptadmin.app.AppManager;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.FastOnlineData;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.SuccessData;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.OffOnLineTaskViewPresenter;
import com.jzg.jcptadmin.viewinterface.OffOnLineTaskViewInterface;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by jzg on 2016/4/1.
 */
public class OffOnLineTaskViewActivity extends BaseActivity implements OffOnLineTaskViewInterface {
    @Bind(R.id.tv_operation)
    TextView tvOperation;
    @Bind(R.id.tv_lianxiren)
    TextView tvLianxiren;
    @Bind(R.id.tv_mlianxiren)
    TextView tvMlianxiren;
    @Bind(R.id.rl_lianxiren)
    RelativeLayout rlLianxiren;
    @Bind(R.id.view1)
    View view1;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.tv_mphone)
    TextView tvMphone;
    @Bind(R.id.rl_lianxidianhua)
    RelativeLayout rlLianxidianhua;
    @Bind(R.id.view2)
    View view2;
    @Bind(R.id.tv_area)
    TextView tvArea;
    @Bind(R.id.tv_count)
    TextView tvCount;
    @Bind(R.id.tv_car_count)
    TextView tvCarCount;
    @Bind(R.id.tv_des)
    TextView tvDes;
    @Bind(R.id.bianhao)
    TextView tvBianHao;
    @Bind(R.id.tv_bohui)
    TextView tvBohui;
    @Bind(R.id.ll_bohui)
    LinearLayout llBohui;
    @Bind(R.id.tv_area1)
    TextView tvArea1;
    @Bind(R.id.tv_diqu)
    TextView tvDiqu;
    @Bind(R.id.rl_diqu)
    RelativeLayout rlDiqu;

    private StatusData statusData;
    private ArrayList<String> statusList1 = new ArrayList<>();
    private ListView lvPopupList;
    private PopupWindow pwMyPopWindow;
    private TaskViewStadusAdapter taskViewStadusAdapter;
    private String id;
    private List<StatusData.ItemListEntity.FastOffLineBtnEntity.ItemEntity> staduslist;
       private CarDetails datas;
    private OffOnLineTaskViewPresenter offOnLineTaskViewPresenter;
    private User user;
    private String titleStr;
    private FastOnlineData.AppraiseListEntity appraiseListEntity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offonline_taskview);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        id = intent.getStringExtra(Constant.ACTIVITY_OFFINEID);
        titleStr = intent.getStringExtra("title");
        appraiseListEntity = (FastOnlineData.AppraiseListEntity) intent.getSerializableExtra("datas");
        initData();
        user = appContext.getUser();
        statusData = appContext.getStatus();
        offOnLineTaskViewPresenter = new OffOnLineTaskViewPresenter(DataManager.getInstance());
        offOnLineTaskViewPresenter.attachView(this);
        if (id != null) {
            showDialog();
            offOnLineTaskViewPresenter.loadTaskView();
        }
    }

    private void initData() {
        // intent.putExtra("lianxiren",mDatas.get(position).getContactMan());
//                            intent.putExtra("phone",mDatas.get(position).getContactMobile());
//                            intent.putExtra("address",mDatas.get(position).getContactAddr());
//                            intent.putExtra("orderno",mDatas.get(position).getOrderNo());
//                            intent.putExtra("des",mDatas.get(position).getDes());

        if (appraiseListEntity != null) {
            tvMlianxiren.setText(appraiseListEntity.getContactMan());
            tvMphone.setText(appraiseListEntity.getContactMobile());
            tvArea.setText(appraiseListEntity.getContactAddr());
            tvDes.setText(appraiseListEntity.getDes());
            tvBianHao.setText(appraiseListEntity.getOrderNo());
            tvDiqu.setText(appraiseListEntity.getProvName()+" "+ appraiseListEntity.getCityName());
            if (!TextUtils.isEmpty(appraiseListEntity.getTaskBackReason())) {
                llBohui.setVisibility(View.VISIBLE);
                tvBohui.setText(appraiseListEntity.getTaskBackReason());
            } else {
                llBohui.setVisibility(View.GONE);
            }
        }
//        tvMlianxiren.setText(intent.getStringExtra("lianxiren"));
//        tvMphone.setText(intent.getStringExtra("phone"));
//        tvArea.setText(intent.getStringExtra("address"));
//        tvDes.setText(intent.getStringExtra("des"));
//        tvBianHao.setText(intent.getStringExtra("orderno"));
    }

    private void iniPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.task_detail_popupwindow, null);
        lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
        pwMyPopWindow = new PopupWindow(layout);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        if (taskViewStadusAdapter == null) {
            taskViewStadusAdapter = new TaskViewStadusAdapter(appContext, statusList1);
        }
        lvPopupList.setAdapter(taskViewStadusAdapter);
        lvPopupList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //点击操作回调,筛选操作的功能
                ScreenOperation(statusList1.get(position));
                if (pwMyPopWindow.isShowing()) {
                    pwMyPopWindow.dismiss();// 关闭
                } else {
                    pwMyPopWindow.showAsDropDown(tvOperation);// 显示
                }
            }
        });
        // 控制popupwindow的宽度和高度自适应
        lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
        /*pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 20)
                * NUM_OF_VISIBLE_LIST_ROWS);*/
       /* pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 50)
                * statusList1.size());*/
        pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 20)
                * (statusList1.size() + 1));
        // 控制popupwindow点击屏幕其他地方消失
        pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg_tanchu));// 设置背景图片，不能在布局中设置，要通过代码来设置
        pwMyPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
    }

    public void ScreenOperation(String string) {
        switch (string) {
            case "修改":
//                Intent intent = new Intent(TaskViewActivity.this, PublishTaskActivity.class);
//                intent.putExtra(Constant.ACTIVITY_INSERTID, id + "");
//                intent.putExtra(Constant.ACTIVITY_TASKVIEWDATA, datas);
//                startActivity(intent);
//                finish();
                break;
            case "删除":
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要删除这条数据吗？")
                        .setConfirmText("是的").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                offOnLineTaskViewPresenter.ZyOperationData(user.getUserId() + "", "DelInfo", id, "", "");
                                sDialog.dismissWithAnimation();
                            }
                        }).show();
                break;
            case "退回":
                Intent intent4 = new Intent(this, RejectActivity.class);
                intent4.putExtra("id", id);
                intent4.putExtra("status", "专业线下退回");
                startActivity(intent4);
                AppManager.getAppManager().finishActivity(OfflineDetectionActivity.class);
                break;
            case "恢复":
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要恢复这条数据吗？")
                        .setConfirmText("是").setCancelText("否")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {

                                offOnLineTaskViewPresenter.ZyOperationData(user.getUserId() + "", "HuiFu", id, "", "");
                                sDialog.dismissWithAnimation();
                            }
                        }).show();
                break;
            case "审核":
                Intent intent1 = new Intent(OffOnLineTaskViewActivity.this, ExamineActivity.class);
                intent1.putExtra("id", id);
                intent1.putExtra("type", "ShenHe");
                startActivity(intent1);
                break;

            default:

                break;
        }
    }


    //初始化操作的数据
    private void initOperationData(CarDetails datas) {
        staduslist = statusData.getItemList().getFastOffLineBtn().getItem();
        String[] str1 =  datas.getButtonStr().split(",");
        Logger.e("线下操作数据" +  datas.getButtonStr());
        for (int i = 0; i < staduslist.size(); i++) {
            for (int j = 0; j < str1.length; j++) {
                if (staduslist.get(i).getId().equals(str1[j])) {
                    statusList1.add(staduslist.get(i).getValue());
                }
            }
        }
        //  statusList1.add("删除");
        if (statusList1.size() <= 0) {
            tvOperation.setVisibility(View.GONE);
        } else {
            tvOperation.setVisibility(View.VISIBLE);
        }
        iniPopupWindow();
    }

    @OnClick({R.id.tv_operation})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_operation://操作
                if (pwMyPopWindow != null && pwMyPopWindow.isShowing()) {
                    pwMyPopWindow.dismiss();// 关闭
                } else {
                    if (pwMyPopWindow != null)
                        pwMyPopWindow.showAsDropDown(tvOperation);// 显示
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void showViewDatas(CarDetails datas) {
        if (datas != null&&datas.getStatus().equals("100")) {
            dismissDialog();
//            this.datas = datas;
            //初始化操作的数据
            if (statusData != null) {
                initOperationData(datas);
            } else {
                MyToast.showShort("无操作数据");
            }
            //  initData();
            Logger.e("返回详情数据" + datas.toString());
        }else{
            MyToast.showShort("无操作数据");
        }

    }

    @Override
    public void OperationDatas(SuccessData datas) {
//        if (datas.getStatus() == 100) {
//            dismissDialog();
//            Intent intent = new Intent(OffOnLineTaskViewActivity.this, YiXinActivity.class);
//            intent.putExtra("title", titleStr);
//            startActivity(intent);
//            finish();
//        } else {
//            Toast.makeText(OffOnLineTaskViewActivity.this, datas.getMsg(), Toast.LENGTH_SHORT).show();
//        }


    }

    @Override
    public Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("taskid", id);
        params.put("userid", user.getUserId() + "");
        params.put("tokenid", "6");
        params.put("type", "details");
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));
        Logger.e("线下详情数据" + params.toString());
        return params;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        offOnLineTaskViewPresenter.detachView();
    }

    @Override
    public void showError(String error) {
        super.showError(error);
        dismissDialog();
        MyToast.showShort(Constant.errr_net);
    }
}
